package com.study.leetcode;

public class _34 {

    public static int find(int[] nums, int target) {
        int l = 0;
        int r = nums.length - 1;
        int mid = -1;

        while (r >= l) {
            mid = (l + r) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return -1;
    }


    public static int findFirst(int[] nums, int target) {
        int l = 0;
        int r = nums.length - 1;
        int mid = -1;
        while (r >= l) {
            mid = (l + r) / 2;
            if (nums[mid] == target) {
                if (mid == 0 || nums[mid - 1] != target) {
                    return mid;
                }
                r = mid - 1;
            } else if (nums[mid] > target) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return -1;
    }

    public static int findLast(int[] nums, int target) {
        int l = 0;
        int r = nums.length - 1;
        int mid = -1;
        while (r >= l) {
            mid = (l + r) / 2;
            if (nums[mid] == target) {
                if (mid == nums.length - 1 || nums[mid + 1] != target) {
                    return mid;
                }
                l = mid + 1;
            } else if (nums[mid] > target) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] nums = {5, 7, 7, 8, 8, 10};
        int target = 6;
        int i = find(nums, target);
        System.out.println(i);
        int first = findFirst(nums, target);
        System.out.println(first);
        int last = findLast(nums, target);
        System.out.println(last);
    }
}
